package by.bucha.testproject.content.database;

import by.bucha.testproject.content.database.tables.WorkerTable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class DatabaseHelper extends SQLiteOpenHelper {

	/** The constant database version number. */
	public static final int DATABASE_VERSION = 1;

	/** The constant database file name. */
	public static final String DATABASE_NAME = "by.bucha.testapp";

	public DatabaseHelper(final Context context, final CursorFactory factory) {
		super(context, DATABASE_NAME, factory, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			db.beginTransaction();
			db.execSQL(WorkerTable.CREATE_WORKER_TABLE_SQL);
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		try {
			db.beginTransaction();
			db.execSQL(WorkerTable.CREATE_WORKER_TABLE_SQL);
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		onCreate(db);
	}

	public Cursor getTasks(String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy, String table) {
		Cursor cursor = getReadableDatabase().query(table, columns, selection,
				selectionArgs, groupBy, having, orderBy);
		return cursor;
	}

	public int deleteTasks(String selection, final String[] selectionArgs,
			String table) {
		int count = getWritableDatabase().delete(table, selection,
				selectionArgs);
		return count;
	}

	public int updateTasks(ContentValues values, String selection,
			String[] selectionArgs, String table) {
		int count = getWritableDatabase().update(table, values, selection,
				selectionArgs);
		return count;
	}

	public long addTasks(ContentValues values, String table) {
		return getWritableDatabase().insert(table, null, values);
	}

}
